{-# LANGUAGE OverloadedStrings,InstanceSigs,ViewPatterns    #-}
{-# LANGUAGE QuasiQuotes,MultiParamTypeClasses,ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell,TypeFamilies,FlexibleInstances #-}
{-# LANGUAGE RecordWildCards#-}
module CMS.Data where
--import Data.Set  (member)
import Yesod.Static
import Yesod
import Database.Persist.Sqlite
import qualified App.Common.Types as I
import qualified App.UserCenter.Core as UC
import App.UserCenter.DB
import Data.Int
import Data.Text
import qualified App.LibTemplate.LibTemplate as Tpl
import Data.Aeson
import App.LibTemplate.LibTemplate
import Text.Blaze.Html
data Master = Master {
  getConnectionPool::ConnectionPool,
  getStatic :: Static,
  tplEngine :: Maybe Tpl.Handle
}

mkYesodData "Master" [parseRoutes|
/ HomeR GET
/article               ArticleHomeR GET
/article/cate/#Int64   ArticleCateListR GET
/article/#Int64        ArticleR GET
/user/login            LoginR GET POST
/user/logout           LogoutR GET
/user/register         RegisterR GET POST
/user/captcha          CaptchaR GET
/user/profile          UserProfileR   GET POST
/user/cpwd             UserChangePwdR GET POST

/idea IdeaR:
  /home                      IdeaHomeR       GET
  /add                       IdeaAddR        POST
  /list/#Int                 IdeaListR       GET
/static StaticR Static getStatic

/admin AdminR:
  /index                         AdminHomeR           GET
  /user/list                     AdminUserListR       GET
  /article/cate_list             AdminArticleCateR    GET
  /article/cate_del              AdminArticleCateDelR POST
  /article/cate_add              AdminArticleCateAddR POST
  /article/article_list/#Int64   AdminArticleListR    GET
  /article/article_add           AdminArticleAddR     GET POST
  /article/article_del           AdminArticleDelR     POST
  /article/article_edit/#Int64   AdminArticleEditorR  GET POST

/api APIR:
  /article_list/#Int APIArticleListR GET
  /article/#Int      APIArticleR     GET
|]


instance Yesod Master where
  approot = ApprootStatic "https://seija.me"
  authRoute _ = Just LoginR
  isAuthorized (AdminR _) _writable = do
    loginUser <- UC.getLoginUser
    case loginUser of
        Nothing -> return AuthenticationRequired
        Just user -> return $ if userRoleType user > 0
                              then  Authorized
                              else  AuthenticationRequired
  isAuthorized (IdeaR _) _writable = maybe AuthenticationRequired (const Authorized) <$> UC.getLoginUserId
  isAuthorized _ _ = return Authorized

instance YesodPersist Master where
  type YesodPersistBackend Master = SqlBackend
  runDB::YesodDB Master a -> HandlerFor Master a
  runDB action = do
    Master  pool _ _ <- getYesod
    runSqlPool action pool

instance RenderMessage Master FormMessage where
  renderMessage _ _ = defaultFormMessage

instance I.Session (HandlerFor Master) where
    lookupSession sessKey =
      liftHandler $ lookupSession sessKey
    deleteSession delKey =
      liftHandler $ deleteSession delKey
    setSession k v = liftHandler $ setSession k v

instance (YesodPersist site,YesodPersistBackend site ~ SqlBackend) => I.SqlDB (HandlerFor site) where
  runDB  = liftHandler.runDB

instance I.WebAppM (HandlerFor Master)


renderTpl::String -> Value -> Handler Html
renderTpl tplName val = do
  Master _ _ (Just te@Handle{..}) <- getYesod
  txt::Text <- liftIO $ renderTemplate te tplName val
  return  $ preEscapedToHtml txt